//package com.yugao.fintech.antelope.auth.oauth2.service;
//
//import cn.hutool.core.util.StrUtil;
//import com.yugao.fintech.antelope.auth.AuthApi;
//import com.yugao.fintech.antelope.auth.constants.AuthPlatformEnum;
//import com.yugao.fintech.antelope.auth.model.LoginContext;
//import com.yugao.fintech.antelope.auth.model.LoginContextHolder;
//import com.yugao.fintech.antelope.auth.model.entity.AuthLocalUser;
//import com.yugao.fintech.antelope.auth.model.entity.AuthThirdUser;
//import com.yugao.fintech.antelope.auth.model.rqrs.LocalUserGetReq;
//import com.yugao.fintech.antelope.auth.model.rqrs.social.SocialLoginResp;
//import com.yugao.fintech.antelope.auth.oauth2.support.core.ResourceAuthException;
//import com.yugao.fintech.antelope.auth.service.UserThirdAuthService;
//import com.yugao.fintech.antelope.base.model.constants.OauthCons;
//import com.yugao.fintech.antelope.base.model.constants.UserCons;
//import com.yugao.fintech.antelope.base.model.enums.AuthErrorEnum;
//import com.yugao.fintech.antelope.base.model.module.auth.LoginUser;
//import com.yugao.fintech.antelope.base.model.module.auth.UserAccount;
//import com.github.yitter.idgen.YitIdHelper;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.context.annotation.Primary;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.authority.AuthorityUtils;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
//import org.springframework.stereotype.Service;
//
//import java.util.*;
//
///**
// * 用户详细信息
// *
//
// */
//@Slf4j
//@Primary
//@Service
//@RequiredArgsConstructor
//public class MyUserDetailsServiceImpl implements MyUserDetailsService {
//	private final RedisTemplate<String, Object> redisTemplate;
//
//	private final UserThirdAuthService thirdAuthService;
//
//	private final AuthApi authApi;
//
//	/**
//	 * 支持用户名密码, 手机号, 邮箱登录
//	 * @param account 账号
//	 */
//	@Override
//	public UserDetails loadUserByUsername(String account) {
//		LoginContext loginContext = LoginContextHolder.get();
//
////		AuthenticatedUser cache = getAuthenticatedUser(account);
////		if (Objects.nonNull(cache)) {
////			return cache;
////		}
//
//		LoginUser loginUser = loginContext.getLoginUser();
//		loginUser.setLoginTime(System.currentTimeMillis());
//		loginUser.setLoginId(String.valueOf(YitIdHelper.nextId()));
//		UserAccount userAccount;
//
//		try {
//			AuthPlatformEnum authPlatform = loginContext.getAuthPlatform();
//			// 使用社交登录
//			if (!AuthPlatformEnum.LOCAL.equals(authPlatform)) {
//				SocialLoginResp socialLoginResp = LoginContextHolder.get().getSocialLoginResp();
//				String openId = socialLoginResp.getOpenId();
//				String platformCode = authPlatform.getCode();
//				Long userId;
//				AuthThirdUser thirdAuth = thirdAuthService.getByOpenId(authPlatform.getCode(), socialLoginResp.getOpenId());
//				if (Objects.isNull(thirdAuth)) { // 第一次使用第三方登录
//					// 临时生成一个用户id, 后期引导用户绑定已有账号或者新建账号, 在注册绑定接口中, 删除当前登录用户数据
//					// 重新登录
//					userId = YitIdHelper.nextId();
//					AuthThirdUser saveData = AuthThirdUser.builder().userId(userId).loginWay(platformCode)
//							.systemType(loginUser.getSystemType())
//							.openId(openId).build();
//					thirdAuthService.save(saveData);
//				} else {
//					userId = thirdAuth.getUserId();
//				}
//
//				loginUser.setUserId(userId).setOpenId(openId);
//
//				// 查询用户本地授权信息
//				AuthLocalUser localUser = Optional.ofNullable(authApi.getUserByUserId(userId)).orElse(new AuthLocalUser());
//				userAccount = UserAccount.builder().userName(account).email(localUser.getEmail())
//						.phone(localUser.getPhone()).password(localUser.getPassword()).build();
//			} else { // 使用本地登录
//				LocalUserGetReq authReq = LocalUserGetReq.builder().account(account).build();
//				AuthLocalUser localUser = authApi.getAuth(authReq);
//				if (Objects.isNull(localUser)) {
//					throw new ResourceAuthException(AuthErrorEnum.USER_ACCOUNT_NOT_EXIST);
//				}
//
//				userAccount = UserAccount.builder().userName(localUser.getUserName()).email(localUser.getEmail())
//						.phone(localUser.getPhone()).password(localUser.getPassword()).status(localUser.getStatus()).build();
//
//				loginUser.setUserId(localUser.getUserId());
//			}
//
//			loginUser.setUserName(account);
//			loginUser.setAccount(userAccount);
//			this.fillLoginContext(loginUser);
//
//
//
//
//			return buildFromLoginUser(loginUser);
//		} catch (Exception e) {
//			if (e instanceof OAuth2AuthenticationException) {
//				throw e;
//			}
//			log.error("error: ", e);
//			throw new ResourceAuthException(AuthErrorEnum.FAIL);
//		}
//	}
//
//	/**
//	 * 获取被授权的用户
//	 * @return 被授权的用户
//	 */
//	private AuthenticatedUser getAuthenticatedUser(String account) {
//		Object userId = redisTemplate.opsForValue().get(String.format(OauthCons.CACHE_USER_LOGIN_TYPE, account));
//		if (Objects.isNull(userId)) {
//			return null;
//		}
//		Object loginUser = redisTemplate.opsForValue().get(String.format(OauthCons.CACHE_USER_DETAILS, userId));
//		if (Objects.nonNull(loginUser)) {
//			return buildFromLoginUser((LoginUser) loginUser);
//		}
//		return null;
//	}
//
//	public AuthenticatedUser buildFromLoginUser(LoginUser user) {
//
////		Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(authority.getPermissions().stream()
////				.filter(StringUtils::isNotEmpty).distinct().toArray(String[]::new));
//
//		// 这里直接设置*, 权限校验由网关统一实现
//		Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("*:*:*");
//
//        // 构造security用户
//        return new AuthenticatedUser(user.getUserName(), user.getAccount().getPassword(),
//                true, true, true,
//                !StrUtil.equals(user.getStatus(), UserCons.Status.DISABLE), authorities);
//	}
//
//	@Override
//	public int getOrder() {
//		return Integer.MIN_VALUE;
//	}
//
//}
